<template>
 <div v-if="!isLoading">
  <el-button>111</el-button>
   <my-component />
   <RouterView />
 </div>
</template>
<script setup>
const { computed, onMounted, ref } = Vue;
const { RouterView, useRoute } = VueRouter;
import { useUserInfoStore } from "@/store/userInfo.js";
const { SET_OPTIONS, POST_USER_SYNC, setUserInfo } = useUserInfoStore();
SET_OPTIONS();
const isLoading = ref(true);

const userdata = computed(() => {
  return useUserInfoStore().userdata.value;
});

const token = computed(() => {
  return userdata.value.token;
});

init();
async function init() {
  if (typeof localforage !== "undefined" && isBrowser) {
    // 全局注入错误上报
    saveError();
    const {
      SET_LOCALFORAGEJS,
      SET_LOCALFORAGEIMG,
      SET_LOCALFORAGEAPI,
      SET_KEYBORDER_EVENT_KEY,
    } = useUserInfoStore();

    function handleKeyboardEvent(event) {
      if (event.key === "Tab") {
        SET_KEYBORDER_EVENT_KEY("tab");
        return;
      }

      switch (event.keyCode) {
        case 83:
          if (event.ctrlKey && event.code === "KeyS") {
            // 阻止直接保存网页,相当于现在全局的保存已经被禁用了
            event.returnValue = false;
            SET_KEYBORDER_EVENT_KEY("ctrl_s");
          }
      }
    }

    // 获取当前数据库的版本
    const indexDBJS = localforage.createInstance({
      // 数据库名
      name: "kl-db",
      // 表名
      storeName: "js-table",
    });
    const indexDBIMG = localforage.createInstance({
      // 数据库名
      name: "kl-db",
      // 表名
      storeName: "img-table",
    });
    const indexDBAPI = localforage.createInstance({
      // 数据库名
      name: "kl-db",
      // 表名
      storeName: "api-table",
    });

    // 向store下注入相关表对象
    // js缓存表
    SET_LOCALFORAGEJS(indexDBJS);
    // // 图片缓存表
    SET_LOCALFORAGEIMG(indexDBIMG);
    // // 接口缓存表
    SET_LOCALFORAGEAPI(indexDBAPI);

    try {
      let version = await localforage.getItem("version");
      if (version && version !== indexDBVersion) {
        Toast("缓存库版本修改，清空数据库");
        localforage.clear();
        indexDBJS.clear();
        indexDBIMG.clear();
        indexDBAPI.clear();
        localforage.setItem("version", indexDBVersion);
      }
    } catch (e) {
      console.log("清空数据库失败", e);
    }
    const defaultArr = [
      // {
      //   css: "//unpkg.com/element-plus/dist/index.css",
      //   remove: false,
      // },
      {
        css: "//at.alicdn.com/t/c/font_3496364_qli2rm9c8j.css",
        cache: false,
      },
      {
        js: "//unpkg.com/element-plus",
        remove: false,
      },
      // {
      //   js: "https://at.alicdn.com/t/font_3007478_ujgs0gnothg.js?spm=a313x.7781069.1998910419.59&file=font_3007478_ujgs0gnothg.js",
      //   remove: false,
      // },
      {
        js: "https://image.zlketang.com/public/news/others/js/jquery-1.11.3.min.js",
        remove: false,
      },
    ];
    if (isDev) {
      // TODO: 待优化
      // $fetch('/api/server_end')
    }
    getIndexDBJS(defaultArr).finally(async () => {
      // 注册全局组件
      // 获取当前应用实例（需确保 app 实例已挂载）

      const app = getAppInstance();

      // 注册全局组件
      app.use(ElementPlus)
      await sleep(1000)
      console.log('MyComponent',app._context.components.MyComponent);
      isLoading.value = false
      await POST_USER_SYNC();
      // await sleep(1000);
      // 用户邮件推送提示
      const { tipGoEmailDayStatus, tipGoEmailDayType } = userdata.value || {};
      if (tipGoEmailDayStatus == 2 && tipGoEmailDayType == 2 && !isDev) {
        const flag = await elConfirm("前往邮件中心...").catch(() => false);
        if (!flag) return;
        goTo("/push_task_day");
        try {
          // 更新用户信息
          const res = await apis.put_author({
            tipGoEmailDayType: 1,
            need_loading: false,
            _autoTip: false,
          });

          if (isObject(res?.data)) {
            setUserInfo({
              user: res.data,
            });
          }
        } catch (e) {
          Toast(e);
        }
      }
    });

    // 每次都先清空
    SET_KEYBORDER_EVENT_KEY("");

    // 全局按键监听
    window.addEventListener("keydown", handleKeyboardEvent);
    post_async_user();
    // 监听页面退出
    window.addEventListener("beforeunload", post_async_user);
  }
}

function post_async_user() {
  // 只有在生产环境才执行
  if (isDev) return;
  const last_login_out_time_store = localStorage.getItem(
    "last_login_out_time_store"
  );
  const current_time = Date.now();
  // 每1分钟可以上报一次退出状态
  if (
    last_login_out_time_store &&
    current_time - last_login_out_time_store < 60 * 1000
  )
    return;
  fetch(`${BASE_URL}/author/put_author?user_id=${userdata.value._id}`, {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
      Authorization: token.value,
    },
    body: JSON.stringify({
      last_login_out_time: current_time,
    }),
    keepalive: true,
  });
  localStorage.setItem("last_login_out_time_store", current_time);
}

const { isAdmin, isLogin } = useUserInfoStore();
const route = useRoute();

const isShowRecommend = computed(() => {
  return !isPc();
});

const isShowRightMenu = computed(() => {
  return isPc() && isAdmin.value && route.meta.isNeedRightMenu !== false;
});

const isShowGame = computed(() => {
  return isPc() && isLogin.value && route.meta.isShowGame !== false;
});

// 前往游戏主页
function goGame() {
  goTo("/game");
}

const isShowWeatherCity = computed(() => {
  return route?.name === "index" && isPc();
});

const isShowIm = computed(() => {
  return isPc() && isLogin.value && route.meta.isShowIm !== false;
});

const isShowCalendar = computed(() => {
  return isLogin.value && route.meta.isShowCalendar !== false;
});

const keepalive = {
  include: ["index", "interview_test", "menu_list", "aboutMe"],
};

if (isBrowser) {
  sessionStorage.setItem("performance_begin_time", Date.now());
}

onMounted(() => {
  if (isBrowser) {
    sessionStorage.setItem("performance_mounted_time", Date.now());

    let arr = [
      "localhost",
      "192.168.1.7",
      "192.168.60.13",
      "192.168.106.134",
      "192.168.254.134",
      "192.168.100.200",
      "192.168.100.198",
      "192.168.0.101",
    ];
    let { href } = window?.location || {};
    let isFlag = arr.some((item) => {
      return href.includes(item);
    });
    try {
      if (isFlag && !isPc()) {
        let erudaUrl = "//image.zlketang.com/public/zl_wxpub/js/eruda.min.js";
        let xhr = new XMLHttpRequest();
        xhr.open("GET", erudaUrl, false);
        xhr.send();
        eval(xhr.responseText);
        if (window.eruda) window.eruda.init();
        xhr.onerror = function () {};
      }
    } catch (e) {
      Toast(e);
    }
  }
});
</script>

<style>
</style>